package com.cyys.modules.system.service.thirdInterface;

import com.aliyuncs.exceptions.ClientException;
import com.cyys.common.ql.AR;
import com.cyys.common.services.CyysBaseService;
import com.cyys.common.thirdInterface.aliyun.SMSUtil;
import com.cyys.common.utils.StringUtil;
import com.cyys.common.utils.date.DateUtil;
import com.cyys.modules.system.dao.sms.SmsActivateDao;
import com.cyys.modules.system.model.sms.SmsActivate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service("smsActivateService")
@Transactional(readOnly = true)
public class SmsActivateService extends CyysBaseService<SmsActivateDao, SmsActivate> {

	@Transactional(readOnly = false)
	public SmsActivate getByPhone(String phone, Integer isDelete) {
		return dao.getByPhone(phone, isDelete);
	}

	/**
	 * 验证码生成
	 * @param phone
	 * @param templateCode 短信模板code
	 * @param expireMinute
	 */
	@Transactional(readOnly = false)
	public AR sendActivateCode(String phone, String templateCode, Integer expireMinute) {
		SmsActivate smsActivate = dao.getByPhone(phone, 0);
		if(smsActivate == null){
			smsActivate = new SmsActivate();
			smsActivate.setPhone(phone);
			smsActivate.setActivateCode(StringUtil.getNumRandom(6));
			Date date = new Date();
			smsActivate.setDateExpire(DateUtil.addMinute(date, expireMinute));
			dao.insert(smsActivate);
		}else{
			//重新生成验证码和更新过期时间
			smsActivate.setActivateCode(StringUtil.getNumRandom(6));
			Date date = new Date();
			smsActivate.setDateExpire(DateUtil.addMinute(date, expireMinute));
			dao.updateById(smsActivate);
		}
		//调用接口发送验证码
		try {
			Map<String,String> codeMap= new HashMap<String,String>();
			codeMap.put("code",smsActivate.getActivateCode());
			Map<String, String> returnMap= SMSUtil.smsSend(phone, templateCode, codeMap);
			if(!"0".equals(returnMap.get("code"))){
				return AR.failed("验证码发送失败：" + returnMap.get("msg"));
			}
			return AR.ok("验证码发送成功");
		}catch (ClientException e){
			return AR.failed("验证码发送失败：" + e);
		}
	}
	
	/**
	 * 验证码验证
	 * @param phone
	 * @param activateCode
	 * @return
	 * @
	 */
	@Transactional(readOnly = false)
	public AR judgeActivateCode(String phone, String activateCode) {
		SmsActivate smsActivate = dao.getByPhone(phone, 0);
		Date date = new Date();
		if(smsActivate == null || !date.before(smsActivate.getDateExpire())){  //未找到验证码
			return AR.failed("验证码不存在或已过期，请重新发送");
		}
		if(!activateCode.equals(smsActivate.getActivateCode())){
			return AR.failed("验证码错误");
		}
		dao.deleteById(smsActivate.getId());
		return AR.ok("验证成功");
	}
}
